<?php
/**********************************************************************
 *                                                                    *    
 * Copyright (c) 2009 Dmytro Bezhnar. All rights reserved.                *
 *                                                                    *
 **********************************************************************/

/**
 * RewriteBaseManager
 *
 * @version $Id: RewriteBaseManager.php,v 1.32 2008/09/30 13:12:28 sdobrovol Exp $
 */
class RewriteBaseManager extends ORMManager {
	
	/**
	 * Массив языков 
	 */
	public $languages = array();
	
	/**
	 * Ассоциативный массив языков по id  
	 */
	public $languages_by_id = array();
	
	/**
	 * Ассоциативный массив языков по code  
	 */
	public $languages_by_code = array();

	/**
	 * Масив параметров из RewriteRules через /
	 */
	public $path_arr = array();

	/**
	 * Ассоциативный масив распарсеных из директории параметров /
	 */
	public $path_assoc = array();
	
	/*
	 * Контроллер
	 */
	public $target = 'main';

	/*
	 * Действие
	 */
	public $event = '';
	public $skin = '';

	public $lang_code;
	public $change_lang = false;
	
	public $page;
	public $change_page = false;
	
	public $rewrite_enable = false;
	
	/**
	 * Process rewrite rules
	 *
	 */
	public function run() {
		
		if ($GLOBALS['options']['core']['version'] >= 2.0 && !$_REQUEST['core_rewrite_off']) {
			$this->rewrite_enable = true;
		}
		
		# Setup Remote IP
		$this->setup_remote_addr();
		
		# Setup DBCharset 
		$this->setDBCharset();
		# Setup languages
		$this->load_languages();
		
		# Parce param string
		$this->parce_param();

		if ($this->rewrite_enable) $this->setup_target_event();
		
		if ($this->event=='clear_cache') $clear= new ClearObj();

		if (count($this->path_arr)) {
			$this->make_param_assoc();
		}
		
		if ($this->rewrite_enable && $this->change_page) $this->path_assoc['page'] = $this->page;
		
		# Setup languages
		//$this->setup_languages();
		
		# Detect partner id
		$this->detect_partner();
		//func_log(print_r($this,true),'_trace',LOG_ERR);
	}
	

	protected function setDBCharset() {
		$_SESSION['lang_mysql_charset'] = $GLOBALS['options']['locale']['db_charset'];
		if ($_SESSION['lang_mysql_charset'] == '') {
			$_SESSION['lang_mysql_charset'] = 'cp1251';
		}
	}
	
	/**
	 * Parsing request string
	 */
	protected function parce_param() {
		global $options;
		$script_name = $_SERVER[SCRIPT_NAME];
		
		//$lang_code = $options['multilanguage']['lang'];

		if (isset($_SESSION['lang_code'])) { $lang_code = $_SESSION['lang_code']; }
		if (isset($_REQUEST['lang_code'])) { $lang_code = $_REQUEST['lang_code']; }
		if (isset($_GET['lang_id']))   { 
			if (isset($this->languages_by_id[$_GET['lang_id']])) {
				$lang_code = $this->languages_by_id[$_GET['lang_id']]['lang_code'];
				$this->change_lang = true;
			}
		}
		if (isset($_GET['lang_code'])) { 
			$lang_code = $_GET['lang_code'];
			$this->change_lang = true;
		}
		
		if (isset($_REQUEST['target'])) {
			$this->target = $_REQUEST['target'];
		}
		
		if (isset($_REQUEST['event'])) {
			$this->event = $_REQUEST['event'];
		}
		
		if (isset($_REQUEST['skin'])) {
			$this->skin = $this->delSpecChars($_REQUEST['skin']);
		}
		
		func_log('Ok '.$_SERVER['REDIRECT_URL'].' > '.$_SERVER['REQUEST_URI'],'_trace',LOG_INFO);
		if (isset($_SERVER['REDIRECT_URL']) and $this->rewrite_enable) {
			//func_log('Ok '.$_SERVER['REDIRECT_URL'].' > '.$_SERVER['REQUEST_URI'],'_trace',LOG_ERR);
			$script_name = $_SERVER['REDIRECT_URL'];
			//$script_name = str_replace($options['site']['BasePath'],'',$script_name);
			$script_name = preg_replace(':^'.$options['site']['BasePath'].':','',$script_name);
			$path_arr = split('/',$script_name);
			$matches = array();
			if (preg_match('/^\d+.html/', $path_arr[count($path_arr)-1], $matches)){
				$this->page = array_pop($path_arr)*1;
				$this->change_page = true;
			}
			
			$this->target = array_shift($path_arr);
			if (isset($this->languages_by_code[strtolower($this->target)])) {
				$lang_code = strtolower($this->target);
				$this->change_lang = true;
				$this->target = array_shift($path_arr);
			}
			$this->path_arr = $path_arr;
		}
		//func_log(print_r($this,true),'_trace',LOG_ERR);
		
		if ($this->target == '') {
			$this->target = 'main';
		} else {
			$this->target = $this->delSpecChars($this->target);
		}
		
		$this->lang_code = $lang_code;
		func_log(print_r($_GET,true),'_trace',LOG_INFO);
	}

	/**
	 * Обработчик параметров, которые распарсились из пути запуска скрипта
	 */
	function make_param_assoc() {
		$key_flag = false;
		foreach ($this->path_arr as $value) {
			$key_flag = !$key_flag;
			if ($key_flag) {
				$key = $value;
			} else {
				if (strlen($key)) {
					$this->path_assoc[$key] = $value;
				} 
			}
		}
	}
	
	function setup_target_event() {
		$data = $this->getQuery()->from('TargetAliasesDBO')->where("target_alias = '$this->target'")->useResultCache(true,$GLOBALS['options']['memcache_core']['target_alias_time'])->fetchOne()->toArray();
		if (is_array($data)) {
			$this->target = $data['target'];
			if ($data['event'] != '') {
				$this->event = $data['event'];
			} else {
				if (count($this->path_arr)) {
					$this->event = array_shift($this->path_arr);
				}
			} 
		} else {
			if (count($this->path_arr)) {
				$this->event = array_shift($this->path_arr);
			}
		}
		$this->event = $this->checkTextForMysql($this->event);
	}
	
	/**
	 * Delete All character exept [A-Za-z0-9] and '_'  
	 */
	function delSpecChars($str) { return preg_replace('/[^\w]/','',$str); }
	
	/**
	 * Detect Partner ID
	 */
	protected function detect_partner() {
		$server_name = strtolower($_SERVER['SERVER_NAME']);
		$partner_cache_time = $GLOBALS['options']['memcache_core']['partner_time'];
		if ($partner_cache_time<=0){
			$partner_cache_time = $GLOBALS['options']['memcache']['time_result_cache'];
		}
		
		$this->partners = $this->getQuery()->select('alias,site_id')->from('SitesAliasDBO')->useResultCache(true,$partner_cache_time)->fetchArray();
		$this->partners = $this->getAssArray($this->partners,'alias','site_id');
		$this->partner_id = $this->partners[$server_name];
		func_log('Partner_id: '.$this->partner_id.', Server name:'.$server_name,'_server_name',LOG_INFO);
		if ($this->partner_id == 0) {
			func_log('Partner_id: '.$this->partner_id.', Server name:'.$server_name,'_server_name',LOG_ERR);
			func_log(print_r($this->partners,true),'_server_name',LOG_ERR);
			$this->partner_id = 1; 
		}
		$_SESSION['partner_id']=$this->partner_id;
		$_SESSION['partner_hostname']=$server_name;
	}
	
	/**
	 * Load Language Array  
	 */
	protected function load_languages() {
        $this->languages = $this->getQuery()->from('langDBO')->useResultCache(true,$GLOBALS['options']['memcache_core']['lang_time'])->fetchArray();
		if (!count($this->languages)) {
			func_log('ERROR: table "lang" is not loaded, try without cache...!','_lang',LOG_ERR);
			$this->languages = $this->getQuery()->from('langDBO')->useResultCache(true,$GLOBALS['options']['memcache_core']['lang_time'])->fetchArray();
		}

		if (!isset($GLOBALS['options']['multilanguage']['lang'])) {
			func_log('ERROR: [multilanguage][lang] is not set in config!','_lang',LOG_ERR);
			$GLOBALS['options']['multilanguage']['lang'] = $this->languages[0]['lang_code']; 
		}
		foreach ($this->languages as &$lang) {
			$this->languages_by_id[$lang['lang_id']] = $lang;  
			$this->languages_by_code[$lang['lang_code']] = $lang;  
		}
	}
	
	/**
	 * Setup global Language Variables   
	 */
	public function setup_languages($parson_id=0) {
		$common_database=ucfirst(strtolower($GLOBALS['options']['passport']['database']));
		if ($this->lang_code == '') {
			$this->lang_code = $GLOBALS['options']['multilanguage']['lang'];
			if ($parson_id) {
				# select from clients
				$lang_code = $this->getQuery()->select('lang_code')->from($common_database.'_ClientsDBO')->where('clientID=115')->fetchOne()->toArray();
				$lang_code = $lang_code['lang_code'];
				if (isset($this->languages_by_code[$lang_code]) and ($lang_code != $this->lang_code)) {
					$this->change_lang = true;
    	 			$this->lang_code = $lang_code; 
				}
			}
		}
		if ($this->change_lang) {
			if ($parson_id) {
    	 		$this->getQuery()->update($common_database.'_ClientsDBO')->set('lang_code',"'$this->lang_code'")->where('clientID='.$parson_id)->execute();
			}
		}
		if ($this->lang_code == '') {
			func_log('ERROR: Cannot setup language code!',$this->class_name,LOG_ERR);
			$this->lang_code = 'ru';
		}
		$this->lang_id = $this->languages_by_code[$this->lang_code]['lang_id'];
		if ($this->lang_id == 0) {
			func_log('ERROR: Cannot setup language id!',$this->class_name,LOG_ERR);
			$this->lang_id = 2;
		}
		
		# setup Languages 
		define('ria_lang_code',$this->lang_code);
		define('ria_lang_id',$this->lang_id);
		
		$_SESSION['lang_code'] = ria_lang_code; 
		$_SESSION['lang_id']   = ria_lang_id;

		$_SESSION['lang_web_charset']=$this->languages_by_code[$this->lang_code]['web_charset'];
		$_SESSION['lang_mysql_charset']=$this->languages_by_code[$this->lang_code]['mysql_charset'];
		
		if ($GLOBALS['riaZoneType'] !='crontab') {
			setcookie('lang_code',ria_lang_code,time()+60*60*24*365,$GLOBALS['options']['site']['BasePath']);
 		}
 		
    	if ($GLOBALS['options']['multilanguage']['lang'] != $_SESSION['lang_code']) {
    	 	$_SESSION['lang_url'] = $_SESSION['lang_code'].'/';
    	} else {
    	 	$_SESSION['lang_url'] = '';
    	}
    	
    	/* set system locale for current lang 
    	 if defined in project lang table */ 
    	if ($this->languages_by_id[$_SESSION['lang_id']]['system_locale']!=''){
    	    $_SESSION['lang_system_locale'] = $this->languages_by_id[$_SESSION['lang_id']]['system_locale'];
    	    setlocale ( LC_CTYPE, $_SESSION['lang_system_locale']);
    	}
	}
	
    /**
     * Устанавливаются в константи REMOTE_ADDR(числовое значение) и REMOTE_ADDR_STR значение IP
     */
	protected function setup_remote_addr() {
		if ($_SERVER['HTTP_X_REAL_IP'] != '') {
			$ip = $_SERVER['HTTP_X_REAL_IP'];
		} else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		$this->remote_addr_str = $ip;
		$this->remote_addr = ip2long($ip);
		define('REMOTE_ADDR',$this->remote_addr);
		define('REMOTE_ADDR_STR',$ip);
	}

	
/**#@+
 * Service Manager functions
 */
	
	/**
	 * Get Info about partner ftom sites Table
	 * @param integer $partner_id
	 * @return array() of parner properties
	 */
	public function get_partner_info($partner_id=0) {
		if ($partner_id == 0) { $partner_id = $this->partner_id; }
		$partner_cache_time = $GLOBALS['options']['memcache_core']['partner_time'];
		$sites_object = $this->getQuery()->from('SitesDBO')->where('site_id='.$partner_id)->useResultCache(true,$partner_cache_time)->fetchOne();
		if (is_object($sites_object))
		{
			return $sites_object->toArray();
		}else{
			return false;
		}
	}
	
    public function setCharset($db_charset) {
        $_SESSION['lang_mysql_charset'] = $db_charset;
        $this->getCurrentConnection()->setCharset($db_charset);       
    }

/**#@-*/
	
}

?>
